package dao

import (
	"context"

	"github.com/nsqio/go-nsq"
	"github.com/patrickmn/go-cache"
	"gorm.io/gorm"

	"wxpay/internal/model"
	"wxpay/pkg/merrors"
)

type AliFaceToFaceSign interface {
	// 创建保存进件
	Save(ctx context.Context, tx *gorm.DB, m *model.AlipayAgentSign) error
	// 根据品牌业务单号查询申请
	QueryByBizNo(_ context.Context, db *gorm.DB, brandId, bizApplyNo string) (*model.AlipayAgentSign, error)
	// 根据申请编号查询
	QueryByApplyNo(_ context.Context, db *gorm.DB, applyNo string) (*model.AlipayAgentSign, error)
}

type ffSignRepo struct {
	*gorm.DB
	producer *nsq.Producer
	cache    *cache.Cache
}

func NewAliFaceToFaceSignRepo(d *gorm.DB, p *nsq.Producer, c *cache.Cache) *ffSignRepo {
	return &ffSignRepo{
		DB:       d,
		producer: p,
		cache:    c,
	}
}

// 新建进件申请
func (f *ffSignRepo) Save(_ context.Context, tx *gorm.DB, m *model.AlipayAgentSign) error {
	const op merrors.Op = "AliFaceToFaceSign.Save"
	if err := tx.Save(m).Error; err != nil {
		return merrors.E(op, merrors.DBError, err, merrors.ErrInternal)
	}
	return nil
}

// 根据品牌查询申请
func (f *ffSignRepo) QueryByBizNo(_ context.Context, db *gorm.DB, brandId, bizApplyNo string) (*model.AlipayAgentSign, error) {
	const op merrors.Op = "AliFaceToFaceSign.QueryByBizNo"
	res := &model.AlipayAgentSign{}
	if err := db.Model(&model.AlipayAgentSign{}).Where("brand_id = ?", brandId).Where("biz_apply_no = ?", bizApplyNo).First(res).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, merrors.E(op, merrors.NotExist, merrors.ErrNotFound, err)
		} else {
			return nil, merrors.E(op, merrors.DBError, merrors.ErrInternal, err)
		}
	}
	return res, nil
}

// 根据申请编号查询
func (f *ffSignRepo) QueryByApplyNo(_ context.Context, db *gorm.DB, applyNo string) (*model.AlipayAgentSign, error) {
	const op merrors.Op = "AliFaceToFaceSign.QueryByApplyNo"
	res := &model.AlipayAgentSign{}
	if err := db.Model(&model.AlipayAgentSign{}).Where("apply_no = ?", applyNo).First(res).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, merrors.E(op, merrors.NotExist, merrors.ErrNotFound, err)
		} else {
			return nil, merrors.E(op, merrors.DBError, merrors.ErrInternal, err)
		}
	}
	return res, nil
}
